# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError


class CpqBom(models.Model):
    _name = 'cpq.bom'
    _description = 'BOM版本'
    _rec_name = 'name'
    _order = 'create_date desc'

    # 基础信息
    name = fields.Char('BOM名称', compute='_compute_name', store=True, index=True)
    project_id = fields.Many2one(
        'cpq.project',
        '项目',
        required=True,
        ondelete='cascade',
        index=True
    )
    
    # 版本信息
    version_type = fields.Selection([
        ('l1', 'L1-初版'),
        ('l2', 'L2-竞标锁定版'),
        ('l3', 'L3-SOP版')
    ], string='版本类型', required=True, index=True)
    
    version_number = fields.Char('版本号', help='如：V1, V2, A0')
    
    # 状态
    state = fields.Selection([
        ('draft', '草稿'),
        ('confirmed', '已确认'),
        ('locked', '已锁定'),
        ('cancelled', '已取消')
    ], string='状态', default='draft', index=True)
    
    is_locked = fields.Boolean('是否锁定', default=False, index=True)
    locked_date = fields.Datetime('锁定时间', readonly=True)
    locked_by_id = fields.Integer('锁定人ID', readonly=True, help='锁定用户的ID')
    locked_by_name = fields.Char('锁定人', compute='_compute_locked_by_name', store=True)
    
    @api.depends('locked_by_id')
    def _compute_locked_by_name(self):
        """计算锁定人名称"""
        for record in self:
            if record.locked_by_id:
                # 直接存储用户ID，显示时使用ID
                record.locked_by_name = f'用户ID: {record.locked_by_id}'
            else:
                record.locked_by_name = False
    
    # BOM明细
    line_ids = fields.One2many('cpq.bom.line', 'bom_id', 'BOM明细')
    
    # 统计
    line_count = fields.Integer('行数', compute='_compute_line_count', store=True)
    
    # 对比相关
    previous_bom_id = fields.Many2one('cpq.bom', '原版本', help='用于版本对比')
    comparison_result_id = fields.Many2one(
        'cpq.bom.comparison',
        '对比结果',
        help='版本对比结果记录'
    )
    
    # 货币（从项目继承）
    currency_id = fields.Many2one(
        'cpq.currency',
        '货币',
        related='project_id.currency_id',
        store=True
    )
    
    # 备注
    notes = fields.Text('备注')
    
    @api.depends('project_id', 'project_id.name', 'version_type', 'version_number')
    def _compute_name(self):
        for record in self:
            project_name = record.project_id.name if record.project_id else ''
            version_type_name = dict(record._fields['version_type'].selection).get(record.version_type, '')
            version_num = record.version_number or ''
            if version_num:
                record.name = f'{project_name} - {version_type_name} - {version_num}'
            else:
                record.name = f'{project_name} - {version_type_name}'
    
    @api.depends('line_ids')
    def _compute_line_count(self):
        for record in self:
            record.line_count = len(record.line_ids)
    
    def action_lock(self):
        """锁定BOM版本"""
        self.ensure_one()
        if self.state != 'confirmed':
            raise UserError('只有已确认的BOM才能锁定！')
        self.write({
            'state': 'locked',
            'is_locked': True,
            'locked_date': fields.Datetime.now(),
            'locked_by_id': self.env.user.id
        })
        return True
    
    def action_unlock(self):
        """解锁BOM版本（需权限）"""
        self.ensure_one()
        # TODO: 添加权限检查（仅管理员或成本经理可解锁）
        self.write({
            'state': 'confirmed',
            'is_locked': False,
            'locked_date': False,
            'locked_by_id': False
        })
        return True
    
    def action_confirm(self):
        """确认BOM版本"""
        self.ensure_one()
        self.write({'state': 'confirmed'})
        return True

